import cTitle from "components/title";
import dayjs from 'dayjs';
// import { Loading } from 'element-ui';
const imgTitle = require('../../../assets/images/lucky_draw-title@2x.png');
const questionMark = require('../../../assets/images/icon-question-mark@2x.png');
const prizeResultBg = require('../../../assets/images/lottery-popup-bg@2x.png');
const popupCloseIcon = require('../../../assets/images/close_iocn.png');
const redBg = require('../../../assets/images/red-bg.png');
export default {
  components: { cTitle },
  data() {
    return {
      activity_id: null,
      reward_id: null,
      imgTitle,
      // notStart-未开始, underway-进行中, ended-已结束
      lotteryStatus: 'notStart',
      // 倒计时(毫秒)
      countDown: null,
      countDownShow: true,
      // 活动时长
      duration: 0,
      mustIntegral: 0,
      // 倒计时图片地址
      countDownImg: null,
      questionMark,
      // 倒计时定时器
      countDownTimer: null,
      partInTeamTimer: null,
      // 中奖结果弹窗
      prizeResultVisible: false,
      prizeResultBg,
      popupCloseIcon,
      redBg,
      user: [{}, {}, {}, {}, {}],
      rulesText: '',
      winners: [],
      page: 1,
      pageSize: 10,
      loading: false,
      finished: false,
      refreshing: false,
      isWinner: 0,
      winnerIntegral: 0,
      // 是否当前页面
      isCurrentPage: true
    };
  },

  methods: {
    /**
     * 获取开奖组队人员
     */
    partInTeam: function() {
      const that = this;
      $http.get('plugin.luck-new-draw.api.activity.partInTeam', { activity_id: this.activity_id, reward_id: this.reward_id }).then(function(response) {
        const { result, data } = response;
        if (result == 1) {
          const { list, countdown, first_time, integral, status, now_time } = data;
          that.user = list;
          that.mustIntegral = integral;
          that.duration = countdown;
          // status: 1-进行中, 2-已解散, 3-已开奖
          if (status == 1) {
            // 活动总时长(毫秒)
            const duration = countdown * 60 * 1000;
            // 距活动结束时长(毫秒)
            that.countDown = duration - dayjs(now_time).diff(dayjs(first_time));
          } else if(status == 2) {
            clearInterval(that.partInTeamTimer);
            that.countDownShow = false;
            that.$dialog.alert({ message: '活动已解散' })
              .then(function() {
                that.$router.replace(that.fun.getUrl('IntegralActivities'));
              });
          }
          if (list.length < 5) {
            // 参与用户不足5人用'{}'补充
            const emptyNum = 5 - list.length;
            for (let i = 0; i < emptyNum; i++) {
              that.user.push({});
            }
          } else {
            // 是否已查看过中间结果，查看过则提示活动结束，否则进入倒计时
            const viewWinningResult = localStorage.getItem('viewWinningResult');
            if (viewWinningResult) {
              that.$dialog.alert({ message: '活动已结束' })
                .then(function() {
                  that.$router.replace(that.fun.getUrl('IntegralActivities'));
                });
            } else {
              // 满足5人清除查询定时器，去查询中奖结果
              clearInterval(that.partInTeamTimer);
              that.startLottery();
            }
            
          }
        } else {
          that.$dialog.alert({ message: response.msg || '验证错误' });
        }
      });
    },

    /**
     * 查询中奖
     */
    getPrizeWinner: function() {
      // 图片倒计时
      // this.startLottery();
      // 隐藏倒计时
      this.countDownShow = false;
      const that = this;
      $http.get('plugin.luck-new-draw.api.activity.getPrizeWinner', { reward_id: this.reward_id }).then(function(response) {
        const { result, data } = response;
        if (result == 1) {
          if(data.is_winner) {
            // 中奖
            that.isWinner = data.is_winner;
            that.winnerIntegral = data.integral;
          }
          that.prizeResultVisible = true;
          localStorage.setItem('viewWinningResult', true);
        } else {
          that.$dialog.alert({ message: response.msg || '验证错误' });
        }
      });
    },

    /**
     * 获取中奖列表
     */
    getWinnerList:function() {
      const that = this;
      $http.get('plugin.luck-new-draw.api.activity.getWinnerList', { activity_id: this.activity_id, pageSize: this.pageSize, page: this.page }).then(function(response) {
        const { result, data } = response;
        if (result == 1) {
          const { total, list, explain } = data;
          // 规则
          that.rulesText = explain;
          that.winners =  that.winners.concat(list);
          if (that.winners.length >= total) {
            that.finished = true;
          } else {
            that.page++;
          }
        } else {
          that.$dialog.alert({ message: response.msg || '验证错误' });
        }
      }).finally(function() {
        that.loading = false;
        that.refreshing = false;
      });
    },



    /**
     * 列表下拉刷新
     */
    onRefresh: function() {
      // 清空列表数据
      this.finished = false;
      this.winners = [];

      // 重置页码
      this.page = 1;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.getWinnerList();
    },

    /**
     * 抽奖倒计时
     */
    startLottery: function() {
      // 隐藏倒计时
      this.countDownShow = false;
      const that = this;
      this.lotteryStatus = 'underway';
      let num = 10;
      that.countDownImg = require(`../../../assets/images/num/${num}.png`);
      num--;
      this.countDownTimer = setInterval(function() {
        if (num >= 0) {
          that.countDownImg = require(`../../../assets/images/num/${num}.png`);
          num--;
          if (num < 0) {
            clearInterval(that.countDownTimer);
            // 倒计时结束显示中奖结果
            // that.prizeResultVisible = true;
            that.getPrizeWinner();
          }
        }
      }, 1000);
    },

    /**
     * 剩余时间倒计时结束
     */
    countDownFinish: function() {
      if (this.countDown == null || !this.isCurrentPage || !this.countDownShow) {
        return;
      }
      const that = this;
      clearInterval(this.partInTeamTimer);
      this.$dialog.alert({ message: `由于本次参与活动不足5人，${this.duration}分钟内解散，退回冻结积分` }).then(function() {
        that.$router.replace(that.fun.getUrl('IntegralActivities'));
      });
    },

    /**
     * 跳转到获奖记录
     */
    // goAwardRecord: function() {
    //   this.$router.push(this.fun.getUrl('integral_award_record'));
    // },

    /**
     * 查看中奖结果
     */
    viewAwardRecord: function() {
      this.$router.replace(this.fun.getUrl('integral_award_record'));
    },

    /**
     * 页面后退
     */
    pageGoBack: function() {
      this.prizeResultVisible = false;
      this.$router.go(-1);
    }
  },

  activated() {
    const that = this;
    const { activity_id, reward_id} = this.$route.params;
    this.isCurrentPage = true;
    this.activity_id = activity_id;
    this.reward_id = reward_id;
    this.partInTeam();
    this.partInTeamTimer = setInterval(function() {
      that.partInTeam();
    }, 3 * 1000);
  },

  deactivated() {
    this.isCurrentPage = false;
    clearInterval(this.partInTeamTimer);
    clearInterval(this.countDownTimer);
  }
};
